<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DailyChallenge;
use App\Models\User;
use App\Services\DailyChallengeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DailyChallengeController extends Controller
{
    private $dailyChallengeService;

    public function __construct(DailyChallengeService $dailyChallengeService)
    {
        $this->dailyChallengeService = $dailyChallengeService;
    }

    /**
     * 获取今日挑战
     */
    public function today(Request $request)
    {
        $user = $request->user();
        
        try {
            $todayChallenge = $this->dailyChallengeService->getTodayChallenge($user);

            if (!$todayChallenge) {
                return $this->error('今日暂无挑战', 404);
            }

            return $this->success($todayChallenge, '获取今日挑战成功');

        } catch (\Exception $e) {
            return $this->error('获取今日挑战失败', 500);
        }
    }

    /**
     * 完成挑战
     */
    public function complete(DailyChallenge $challenge, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'completion_data' => 'sometimes|array',
        ]);

        if ($validator->fails()) {
            return $this->error('完成数据验证失败', 422, $validator->errors());
        }

        $user = $request->user();
        $completionData = $request->get('completion_data', []);

        try {
            $result = $this->dailyChallengeService->completeChallenge(
                $user, 
                $challenge, 
                $completionData
            );

            if ($result['success']) {
                return $this->success([
                    'challenge' => $result['challenge'],
                    'reward_earned' => $result['reward_earned'],
                    'is_first_completion' => $result['is_first_completion'],
                    'consecutive_days' => $result['consecutive_days'],
                ], '挑战完成！恭喜你！');
            } else {
                return $this->error($result['message'], 400);
            }

        } catch (\Exception $e) {
            return $this->error('完成挑战失败', 500);
        }
    }

    /**
     * 获取挑战历史
     */
    public function history(User $user, Request $request)
    {
        // 检查是否为当前用户或有权限查看
        if ($user->id !== $request->user()->id) {
            return $this->error('无权查看其他用户的挑战历史', 403);
        }

        $page = $request->get('page', 1);
        $perPage = $request->get('per_page', 20);

        try {
            $history = $this->dailyChallengeService->getChallengeHistory($user, $page, $perPage);

            return $this->success($history, '获取挑战历史成功');

        } catch (\Exception $e) {
            return $this->error('获取挑战历史失败', 500);
        }
    }
}